#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
THISDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
ROOTDIR=${THISDIR%/examples}
BUILDDIR=$ROOTDIR/build
BUILDEXAMPLESDIR=$BUILDDIR/examples/examples

prefix="/usr/local"
if [[ $1 != "" ]]; then
    prefix=$1
fi

echo $PATH | grep -q $prefix/bin
ret=$?
if [ $ret -ne 0 ]; then
    export PATH=$PATH:$prefix/bin
fi

echo $PKG_CONFIG_PATH | grep -q $prefix/lib/pkgconfig
ret=$?
if [ $ret -ne 0 ]; then
    export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$prefix/lib/pkgconfig
fi

echo $LD_LIBRARY_PATH | grep -q $prefix/lib
ret=$?
if [ $ret -ne 0 ]; then
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$prefix/lib/
fi

export ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer
export ASAN_OPTIONS=check_initialization_order=1
export CLASSPATH=$CLASSPATH:$prefix/share/java/zcm.jar
export CLASSPATH=$CLASSPATH:$prefix/share/java/zcm-tools.jar
export CLASSPATH=$CLASSPATH:$BUILDEXAMPLESDIR/types/examplezcmtypes.jar
export CLASSPATH=$CLASSPATH:$BUILDEXAMPLESDIR/types/examplezcmtypespfx.jar
export CLASSPATH=$CLASSPATH:$BUILDEXAMPLESDIR/java/example.jar
export ZCM_SPY_LITE_PATH=$BUILDEXAMPLESDIR/types/libexamplezcmtypes.so
export ZCM_DEFAULT_URL=ipc
export JULIA_LOAD_PATH="$JULIA_LOAD_PATH:$prefix/share/julia:$BUILDEXAMPLESDIR/types"
export PATH=$PATH:~/.local/bin
if [ -z ${PYTHON+x} ]; then
    export PYTHON=$(which python)
fi
export PYTHONPATH=$($PYTHON -c "import sys
from distutils.sysconfig import get_python_lib
print(get_python_lib(standard_lib=0, prefix='$prefix/'))")

checkJuliaInstall()
{
    juliaVersion=$(julia --version 2>/dev/null)
    juliaExists=$?
    juliaVersion=$(echo "$juliaVersion" | xargs | cut -d ' ' -f 3)
    if [[ $juliaExists -ne 0 || \
        ("$juliaVersion" != "1.6.0" && "$juliaVersion" != "0.6.4") ]]; then
        return 1
    else
        return 0
    fi
}
checkJuliaInstall
ret=$?
if [ $ret -ne 0 ]; then
    export PATH=$PATH:$ROOTDIR/deps/julia/bin
    checkJuliaInstall
    ret=$?
    if [ $ret -ne 0 ]; then echo "Unable to find julia"; fi
fi
